package com.example.musicwebcon.service;

import com.example.musicwebcon.model.User;
import com.example.musicwebcon.model.UserInfo;
import com.example.musicwebcon.model.dto.UserInfoDTO;
import com.example.musicwebcon.repository.UserInfoRepository;
import com.example.musicwebcon.repository.UserRepository;
import com.example.musicwebcon.service.serviceInterface.IUserInfoService;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Optional;
import java.util.UUID;


@Service
public class UserInfoService implements IUserInfoService {

    @Autowired
    private UserInfoRepository userInfoRepository;

    @Autowired
    private UserRepository userRepository;


    @Override
    public UserInfo add(UserInfoDTO userInfoDTO) {
        // 检查是否已存在对应的 UserInfo
        if (userInfoRepository.existsById(userInfoDTO.getInfoId())) {
            throw new IllegalArgumentException("用户信息已存在，无法重复添加！");
        }

        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(userInfoDTO, userInfo);
        return userInfoRepository.save(userInfo);
    }

    @Override
    public UserInfo get(String infoId) {

        UserInfo userInfo=userInfoRepository.findById(infoId).orElseThrow(() -> {
            throw new IllegalArgumentException("用户不存在，参数异常！");
        });

        return userInfo;
    }

    @Override
    public UserInfo edit(UserInfoDTO userInfoDTO) {
        UserInfo userInfo = userInfoRepository.findById(userInfoDTO.getInfoId())
                .orElseThrow(() -> new IllegalArgumentException("用户信息不存在！"));
        Optional<User> user =userRepository.findById(userInfoDTO.getInfoId());
        if (user.isPresent()) {
            int age = calculateAge(LocalDate.parse(userInfoDTO.getBirthday()));
            // 更新 User 实体中的年龄
            user.get().setAge(age);

            // 保存更新后的 User 实体
            userRepository.save(user.get());
        }else {
            throw new IllegalArgumentException("用户不存在！");
        }

        BeanUtils.copyProperties(userInfoDTO, userInfo, "infoId"); // 防止覆盖主键
        return userInfoRepository.save(userInfo);
    }
    private int calculateAge(LocalDate birthday) {
        LocalDate today = LocalDate.now();
        if (birthday == null) {
            return 0;
        }
        // 计算年龄
        Period period = Period.between(birthday, today);
        return period.getYears();
    }

    private void updateUserAge(String userId, int age) {
        Optional<User> optionalUser = userRepository.findById(userId);
        if (optionalUser.isPresent()) {
            User user = optionalUser.get();
            user.setAge(age);  // 更新年龄
            userRepository.save(user);  // 保存更新到数据库
        }
    }

    @Override
    public void delete(String infoId) {
        userInfoRepository.deleteById(infoId);
    }

    @Override
    public List<UserInfo> getAllUserInfos() {
        return (List<UserInfo>) userInfoRepository.findAll();
    }


    @Value("${avatar.upload.dir}")
    private String uploadDir; // 上传目录（在 application.yml 或 properties 中配置）

    public String saveAvatar(MultipartFile file) {
        // 确保上传目录存在
        File dir = new File(uploadDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }

        // 使用 UUID 生成唯一文件名，防止重名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename != null ? originalFilename.substring(originalFilename.lastIndexOf(".")) : "";
        String fileName = UUID.randomUUID() + extension;

        // 文件保存路径
        File dest = new File(dir, fileName);
        try {
            file.transferTo(dest); // 保存文件
        } catch (IOException e) {
            throw new RuntimeException("文件保存失败：" + e.getMessage());
        }

        // 返回文件的 URL（假设是通过 HTTP 访问）
        return "/uploads/" + fileName;
    }
}
